<template>
	<view id="container">
		<view style="position: fixed;right: 300rpx;top:50rpx;font-size:150rpx;color:yellow;font-weight: bold;"
			v-show="startFlag&&answerCountDown.flag">
			{{answerCountDown.text}}
		</view>
		<logo position="left" :exitShow="exitShow">
		</logo>
		<view id="question">
			<view id="countdown" v-if="countdownFlag">
				<uni-countdown :show-day="false" :showHour="false" :showMinute="false" :second="3" color="#fff"
					@timeup="start()" :font-size="100" />
			</view>
			<view v-show="comeFlag">
				<view>
					<h3>房间号:{{zoomCode}}</h3>
				</view>
				<view class="user-list">
					<view class="user" v-for="(item,index) in 6">
						<view v-if="userList[index]==null">
							<view class="circular" v-if="userList[index]==null">+</view>
							<h5>{{index+1}}号选手</h5>
						</view>
						<view v-else>
							<view class="ready" v-show="userList[index].ready">
								<image src="@/static/img/ready.png" mode="widthFix" style="width:50rpx;"></image>
							</view>
							<image class="circular" src="@/static/img/logo.png"></image>
							<h5 :class="userList[index].userId==user.userId?'yellow':''">{{userList[index].nickName}}
							</h5>
						</view>
					</view>
					<!-- <view id="ready-btn">
						<button type="primary" @click="onReady" v-show="!readyFlag">准备</button>
					</view> -->
				</view>
			</view>
			<view v-if="startFlag">
				<uni-row :gutter="20">
					<uni-col :span="8">
						<view class="userInfo">
							<view class="middle-circular">{{userIndex}}</view>
							<view class="nickname">
								<view class="score">
									<view>{{userInfo.nickName}}</view>
									<view>
										<label class="current-score">{{userInfo.score}}</label>
										<label>/{{maxScore}}</label>
									</view>
								</view>
								<view>
									<progress :percent="userInfo.score/30*100" class="process" activeColor="#ffecb7"
										backgroundColor="#e67c7f" stroke-width="15" />
								</view>
							</view>
						</view>
						<view v-for="(item,index) in userList">
							<view class="userInfo" v-if="item.userId!=userInfo.userId">
								<view class="mini-circular">{{index+1}}</view>
								<view class="nickname" style="width:60%">
									<view class="score">
										<view>{{item.nickName}}</view>
									</view>
									<view>
										<progress :percent="item.score/30*100" class="process" activeColor="#ffecb7"
											backgroundColor="#e67c7f" stroke-width="15" />
									</view>
								</view>
								<view class="user-score">
									<label>{{item.score}}</label>
								</view>
							</view>
						</view>
					</uni-col>
					<uni-col :span="16">
						<view id="question-wrap">
							<view v-if="questionList[questionIndex]==null">
								您已经答完全部问题，请等待其他人员答完。
							</view>
							<view v-else>
								<view id="question-title">
									{{questionIndex+1}}.{{questionList[questionIndex].questionName}}
									<label v-show="questionList[questionIndex].questionType=='SINGLE'">（选择）</label>
									<label v-show="questionList[questionIndex].questionType=='MULTIPLE'">（选择）</label>
									<label v-show="questionList[questionIndex].questionType=='JUDGE'">（判断）</label>
									<label
										v-show="questionList[questionIndex].questionType=='SINGLE_OR_MULTIPLE'">（选择）</label>
								</view>
								<!-- <view id="option-list" v-if="questionList[questionIndex].questionType=='SINGLE'">
									<view :class="optionWarpCss(item)" v-for="item in ['a','b','c','d']"
										@click="submitAnswer(questionIndex,item)">
										<view :class="wordCss(item)">{{item.toUpperCase()}}</view>
										<view class="text">{{questionList[questionIndex][item]}}</view>
									</view>
									<button type="primary" size="mini" v-show="!overQuestionFlag"
										style="margin-top:30rpx;" @click="submitAnswer(questionIndex,'a')">提交答案</button>
								</view> -->
								<view id="option-list"
									v-if="['SINGLE','MULTIPLE','SINGLE_OR_MULTIPLE'].includes(questionList[questionIndex].questionType)">
									<view :class="mutiOptionWarpCss(item)" v-for="item in ['a','b','c','d','e','f']"
										@click="multipleChange(item.toUpperCase())"
										v-show="questionList[questionIndex][item]!=null&&questionList[questionIndex][item]!=''">
										<view :class="mutiWordCss(item)">{{item.toUpperCase()}}</view>
										<view class="text">{{questionList[questionIndex][item]}} </view>
									</view>
									<view style="display: flex;margin-top:30rpx;">
										<view>
											<button type="primary" size="mini" v-show="!overQuestionFlag"
												@click="submitAnswer(questionIndex,'a')">提交答案</button>
										</view>
										<view v-show="answerRrror" style="margin-left:50rpx;"><label
												style="color:red">请至少选择一个答案!</label></view>
									</view>


								</view>
								<view id="option-list" v-if="questionList[questionIndex].questionType=='JUDGE'">
									<view :class="mutiOptionWarpCss(item)" v-for="item in ['a','b']"
										@click="multipleChange(item.toUpperCase())"
										v-show="questionList[questionIndex][item]!=null&&questionList[questionIndex][item]!=''">
										<view :class="mutiWordCss(item)">{{item.toUpperCase()}}</view>
										<view class="text">{{item=='a'?'正确':'错误'}} </view>
									</view>
									<view style="display: flex;margin-top:30rpx;">
										<view>
											<button type="primary" size="mini" v-show="!overQuestionFlag"
												@click="submitAnswer(questionIndex,'a')">提交答案</button>
										</view>
										<view v-show="answerRrror" style="margin-left:50rpx;"><label
												style="color:red">请至少选择一个答案!</label></view>
									</view>
									<!-- <button type="primary" size="mini" v-show="!overQuestionFlag"
										style="margin-top:30rpx;" @click="submitAnswer(questionIndex,'a')">提交答案</button> -->
								</view>
								<!-- 	<view id="option-list" v-if="questionList[questionIndex].questionType=='JUDGE'">
									<view :class="optionWarpCss(item)" v-for="item in ['a','b']"
										@click="submitAnswer(questionIndex,item.toUpperCase())">
										<view :class="wordCss(item)">{{item}}</view>
										<view class="text">{{item=='a'?'正确':'错误'}}</view>
									</view>
								</view> -->
								<view id="answer" v-show="overQuestionFlag">
									<label
										v-show="['SINGLE','MULTIPLE','SINGLE_OR_MULTIPLE'].includes(questionList[questionIndex].questionType)">正确答案:{{questionList[questionIndex].answer}}</label>
									<label
										v-show="['JUDGE'].includes(questionList[questionIndex].questionType)">正确答案:{{questionList[questionIndex].answer.toUpperCase()=='A'?'正确':'错误'}}</label>
								</view>
							</view>
						</view>
					</uni-col>
				</uni-row>
			</view>
			<view v-if="overFlag">
				<h3 style="text-align: center;">第{{currentIndex-1}}轮比赛排名</h3>
				<uni-table border stripe emptyText="暂无更多数据">
					<uni-tr>
						<uni-th align="center">排名</uni-th>
						<uni-th align="center">昵称</uni-th>
						<uni-th align="center">答题数</uni-th>
						<uni-th align="center">答对题数</uni-th>
						<uni-th align="center">正确率</uni-th>
						<uni-th align="center">分数</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in scoreList">
						<uni-td align="center">{{item.rank}}</uni-td>
						<uni-td align="center">{{item.nickName}}</uni-td>
						<uni-td align="center">{{item.count}}</uni-td>
						<uni-td align="center">{{item.rightCount}}</uni-td>
						<uni-td
							align="center">{{item.count==0?'0':(item.rightCount/item.count*100).toFixed(2)}}%</uni-td>
						<uni-td align="center">{{item.score}}</uni-td>
					</uni-tr>
				</uni-table>
				<!-- 			<button type="primary" @click="onReady" style="margin-top: 20rpx;"
						v-if="currentIndex-1!=maxIndex">准备</button> -->
			</view>
		</view>
	</view>
</template>

<script>
	import logo from "@/component/common/logo.vue";
	import websocket from "@/utils/websocket.js";
	export default {
		components: {
			logo
		},
		data() {
			return {
				websocket: null,
				// socketUrl:import.meta.env.VITE_SOCKET_URL+"socket";
				comeFlag: true,
				readyFlag: false,
				startFlag: false,
				overFlag: false,
				countdownFlag: false,
				answerFlag: false,
				zoomCode: null,
				userIndex: null,
				userList: [],
				questionAllList: [],
				questionList: [],
				questionIndex: 0,
				maxScore: 30,
				score: 0,
				answer: '',
				currentIndex: 1,
				maxIndex: 3, //最终比几轮
				maxQuestionCount: 20,
				rightScore: 3, //答对一题得3分
				scoreList: [], //每一轮排名
				doorRankList: [], //总排名
				tempData: {},
				overQuestionFlag: false, //回答是否结束
				userInfo: null,
				exitShow: true,
				user: this.$user.getUser(),
				answerList: [],
				answerRrror: false,
				answerCountDown: {
					flag: true,
					second: 0,
					text: null
				},
			}
		},
		onLoad(options) {
			this.init(options);
		},
		onUnload() {
			if (this.websocket != null) {
				// this.websocket.closeSocket();
			}
		},
		methods: {
			optionWarpCss(answer) {
				if (this.overQuestionFlag == false) {
					return 'option-wrap';
				}
				if (answer.toUpperCase() == this.answer) {
					if (this.answer == this.questionList[this.questionIndex].answer) {
						return 'option-wrap option-right';
					} else {
						return 'option-wrap option-error shakeHead';
					}
				} else if (this.questionList[this.questionIndex].answer == answer.toUpperCase()) {
					return 'option-wrap option-right';
				} else {
					return 'option-wrap';
				}
				// if (this.questionList[this.questionIndex].answer == answer.toUpperCase()) {
				// 	return 'option-wrap option-right';
				// } else {
				// 	return 'option-wrap option-error shakeHead';
				// }
			},
			wordCss(answer) {
				if (this.overQuestionFlag == false) {
					return 'word';
				}
				if (answer.toUpperCase() == this.answer) {
					if (this.answer == this.questionList[this.questionIndex].answer) {
						return 'word word-right';
					} else {
						return 'word word-error';
					}
				} else if (this.questionList[this.questionIndex].answer == answer.toUpperCase()) {
					return 'word word-right';
				} else {
					return 'word';
				}
				// if (this.questionList[this.questionIndex].answer == answer.toUpperCase()) {
				// 	return 'word word-right';
				// } else {
				// 	return 'word word-error';
				// }
			},
			mutiOptionWarpCss(val) {
				val = val.toUpperCase();
				if (this.overQuestionFlag) {
					if (this.answer.includes(val)) {
						if (this.questionList[this.questionIndex].answer.includes(val)) {
							return 'option-wrap option-right';
						} else {
							return 'option-wrap option-error shakeHead';
						}
					} else {
						if (this.questionList[this.questionIndex].answer.includes(val)) {
							return 'option-wrap option-right shakeHead';
						} else {
							return 'option-wrap';
						}
					}
				} else {
					if (this.answer.includes(val)) {
						return 'option-wrap option-checked';
					} else {
						return 'option-wrap';
					}
				}
			},
			mutiWordCss(val) {
				val = val.toUpperCase();
				if (this.overQuestionFlag) {
					if (this.answer.includes(val)) {
						if (this.questionList[this.questionIndex].answer.includes(val)) {
							return 'word word-right';
						} else {
							return 'word word-error shakeHead';
						}
					} else {
						if (this.questionList[this.questionIndex].answer.includes(val)) {
							return 'word word-right shakeHead';
						} else {
							return 'word';
						}
					}
				} else {
					if (this.answer.includes(val)) {
						return 'word word-checked';
					} else {
						return 'word';
					}
				}
			},
			multipleChange(val) {
				if (this.answerList[this.questionIndex] != null) {
					// },2000);
					return;
				}
				if (this.questionList[this.questionIndex].questionType == 'JUDGE') {
					this.answer = val;
				} else {
					if (this.answer.includes(val)) {
						this.answer = this.answer.replace(val, '');
					} else {
						this.answer += val;
					}
				}
			},
			init(options) {
				const zoomId = options.zoomId;
				this.zoomCode = options.zoomCode;
				const user = this.$user.getUser();
				this.websocket = new websocket(zoomId, user.userId);
				this.websocket.initSocket();
				// //监听信息
				uni.$on('message', this.getMessage);
				const that = this;
				// setTimeout(function(){
				// 	that.answerFlag = false;
				// },1500);
				// setInterval(function(){
				// 	that.answerFlag = false;
				// },2000)
			},
			onReady() {
				this.readyFlag = true;
				this.comeFlag = true;

				this.websocket.sendMsg({
					type: "READY",
					data: {
						index: this.currentIndex
					}
				});
			},
			getMessage(msg) {
				console.log(msg);
				const data = JSON.parse(msg.data);
				// console.log(data);
				switch (data.type) {
					case "MATCHDATA":
						this.revertMatch(data.data);
						break;
						//更新房间人员信息
					case "ZOOMUSERLIST":
						this.setUserIn(data.data);
						break;
					case "START": //开始比赛
						this.tempData = data.data;
						this.readyStart();
						// this.start(data.data);
						break;
					case "OVER_ANSWER":
						this.over(data.data);
						break;
					case "MAXUSER": //人数已满
					case "NOT":
					case "OVER":
						// this.websocket.closeSocket(data.data);
						uni.showToast({
							icon: "none",
							title: data.data,
							duration: 2000,
							success: function() {
								uni.redirectTo({
									url: '/pages/index/index'
								});
							}
						});
						break;
					case "OVERTIMECANCEL":
						this.answerCountDown.flag = false;
						break;
				}
			},

			nextQuestion() {
				this.answerRrror = false;
				this.answerFlag = false;
				this.answer = '';
				this.questionIndex++;
				this.overQuestionFlag = false;
				console.log(this.questionIndex);
				if (this.questionIndex >= this.maxQuestionCount) {
					this.websocket.sendMsg({
						type: "OVERTIMECANCEL"
					});
				}
			},
			readyStart() {
				this.exitShow = false;
				this.overFlag = false;
				this.countdownFlag = true;
				this.answerFlag = false;
			},
			//开始比赛
			start() {
				const data = this.tempData;
				this.countdownFlag = false;
				this.startFlag = true;
				this.comeFlag = false;
				this.answerList = [];
				//开始倒计时
				this.answerCountDown.second = 181;
				this.answerCountDown.flag = true;
				this.answerCountDown.text = null;
				this.answerCountDownStart();
				//如果是第1轮比赛,就把问题记录下来
				if (this.currentIndex == 1) {
					this.questionAllList = data;
				}
				this.questionList = this.questionAllList.slice(this.maxQuestionCount * (this.currentIndex - 1), this
					.maxQuestionCount * this.currentIndex);
				this.questionIndex = 0;
			},
			//结束比赛
			over(data) {
				this.startFlag = false;
				this.overFlag = true;
				this.answer = '';
				this.scoreList = data.doorRanks;
				this.currentIndex++;
				this.score = 0;
				if (this.currentIndex > this.maxIndex) {
					this.exitShow = true;
				}
			},
			setUserIn(userList) {
				const _userInfo = this.$user.getUser();
				for (let i in userList) {
					if (userList[i].userId == _userInfo.userId) {
						this.userIndex = parseInt(i) + 1;
						this.userInfo = userList[i];
						break;
					}
				}
				this.userList = userList;
			},
			revertMatch(match) {
				if (match.status == 'START') {
					if (this.startFlag == false && this.overFlag == true) {
						this.readyStart();
					}
				}
			},
			submitAnswer(questionIndex, val) {
				this.answerRrror = false;
				if (this.answerList[questionIndex] != null) {
					// const that=this;
					// setTimeout(function(){
					// 	that.answerList[questionIndex] = null;
					// },2000);
					return;
				}
				val = val.toUpperCase();
				// if (this.answerFlag) {
				// 	return;
				// }
				this.answerFlag = true;
				//多选题答案按照字母排序
				let score = 0;
				let result = false;
				const that = this;
				if (this.answer.length < 1) {
					this.answerRrror = true;
					return;
				}
				switch (this.questionList[this.questionIndex].questionType) {
					case 'JUDGE':
						// result = val == this.questionList[this.questionIndex].answer ? true : false;
						// this.answer = val;
						// break;
					case 'SINGLE':
						result = this.answer == this.questionList[this.questionIndex].answer ? true : false;
						// this.answer = val;
						break;
					case 'MULTIPLE':
					case 'SINGLE_OR_MULTIPLE':
						const answerList = this.answer.split('');
						answerList.sort((a, b) => {
							return a.toLowerCase().localeCompare(b.toLowerCase());
						});
						this.answer = answerList.join('');
						result = this.answer == this.questionList[this.questionIndex].answer ? true : false;
						break;
					case 'COMPLETION':
						result = this.answer == this.questionList[this.questionIndex].answer ? true : false;
						break;
				}
				score = result ? this.rightScore : 0;
				this.websocket.sendMsg({
					type: "ANSWER",
					data: {
						index: this.currentIndex,
						questionId: this.questionList[this.questionIndex].id,
						questionIndex: this.questionIndex + 1,
						answer: this.answer,
						result: result,
						score: score
					}
				});
				this.score += score;
				if (this.score >= this.maxScore) {
					// this.overFlag=true;
					return;
				}
				this.overQuestionFlag = true;
				// setTimeout(function(){
				// 	that.answerFlag = false;
				// },1500);
				// that.nextQuestion();
				this.answerList[questionIndex] = true;
				if (result) {
					setTimeout(function() {
						that.nextQuestion();
					}, 500);
				} else {
					setTimeout(function() {
						that.nextQuestion();
					}, 2000);
				}
			},
			answerCountDownStart() {
				const that = this;
				// this.answerCountDown.second=180;
				if (this.answerCountDown.second <= 0) {
				} else {
					this.answerCountDown.second--;
					this.answerCountDown.text = parseInt(this.answerCountDown.second / 60) + ":" + String(parseInt(this
						.answerCountDown.second % 60)).padStart(2, '0');
					if (this.answerCountDown.flag&&this.startFlag) {
						setTimeout(that.answerCountDownStart, 1000);
					}
				}
			},
		}
	}
</script>

<style lang="scss">
	@import '@/static/css/start.css';
</style>